#!/usr/bin/env node
// node ./example/index.js

const _Port = require("../dist/index");//.default;

//console.log(_Port);
let path = "";
let ready = false;

function handle(v) {
  console.log("handle-back::", v);
  if (v.type === 'open') {
    console.log('--------: open');
    //open 时候，设备可用还没准备好，收到设备发的信息时，才真正准备好！
  }
  if (v.type === 'data') {
    if(!ready){
      ready =true;
      autoWrite();
    }
  }
}

function autoWrite() {
  if (path == "") return;
  let timeNum = 0;
  db = [49, 98, 99, 100];//1bcd
  let listenId = setInterval(function () {
    console.log("------------", timeNum);
    db[0] = db[0] + 1;
    _Port.write(path, db);
    timeNum++;
    if (timeNum >= 5) {
      clearInterval(listenId);
      listenId = null;
      return;
    }
  }, 10);//1000 , 20
}

function run() {
  _Port.list().then((v) => {
    console.log("list:", v);
    const size = v.length;
    if (size < 1) {
      return;
    }
    const option = v[size - 1];
    console.log("option:", option);
    path = option.path;
    _Port.createPort({ path: path, baudRate: 115200, autoOpen: true }, handle);
    // _Port.close(option.path);
  });
}

run();

/**
write buff : <Buffer 61 62 63 64>
handle:: { type: 'data', data: <Buffer 61 62 63 64 0d 0a> }
 */
// 关闭服务器
// _Port.closeAllWorkers();

// node ./example/index.js
